
import $, { get } from 'jquery';
import { render } from 'less';
import {api} from './api.js'

require('./css/base.css');
require('./css/com.css');
require('./css/style_cy.css');
require('./css/style_chq.css');
require('./css/style-note_zn.css');



$(function(){
    var $pageSize = $('.js_pageSize_chq');
    var $type = $('.js_type_chq');
    var $startTime = $('.is_startTime');
    var $endTime = $('.is_endTime');
    var $queryContentType =$('.js_queryContentType_chq');
    var $queryContent= $('.js_queryContent_chq');

    var $searchBtn = $('.js_search_chq')// 搜索按钮

    var $table = $('table');// 表格主题
    var $nowPage = $('.js_nowPage_chq'); // 当前页码
    var $totalPage = $('.js_totalPage_chq'); // 总页码
    var $prev = $('.prev_chq'); //上一页按钮
    var $next = $('.next_chq'); //下一页按钮
    var $gotoBtn = $('.gotoBtn_chq'); //跳转按钮
    var $gotoInput = $('.js_gotoInput_chq'); // 跳转目标页码

    var $appBtn = $('.js_app_chq');// 预约登记按钮
    var $mask = $('.mask_chq'); // 遮罩层
    var $addForm = $('.js_addForm_chq'); // 合并申请单
    var $addformClose =$('.js_addFormClose_chq'); // 合并申请单关闭按钮
    var $addFormCacle =$('.js_addFormCacle_chq'); // 合并申请单取消按钮
    var $nextPop = $('.js_nextPop_chq'); // 合并申请下一步按钮

    var $loadingICon = $('.loading_chq'); // loading图标

    var $appRegister = $('.js_appRegister_chq') // 弹窗2

    // 表单元素
    var $risPatientId = $('.js_risPatientId_chq');
    var $patientName = $('.js_patientName_chq');
    var $idcard = $('.js_idcard_chq');
    var $birthday = $('.js_birthday_chq');
    var $weight = $('.js_weight_chq');
    var $medicareCardNumber =$('.js_medicareCardNumber_chq');
    var $selfPayCardNumber = $('.js_selfPayCardNumber_chq');
    var $phoneNumber = $('.js_phoneNumber_chq');
    var $familyPhone = $('.js_familyPhone_chq');
    var $company = $('.js_company_chq');
    var $address = $('.js_address_chq');

    var $patientNumber = $('.js_patientNumber_chq');
    var $hospitalizedNumber = $('.js_hospitalizedNumber_chq');
    var $ward = $('.js_ward_chq');
    var $bedNo = $('.js_bedNo_chq');
    var $medicalRecordDescription = $('js_medicalRecordDescription_chq');
    var $clinicDiagnose = $('js_clinicDiagnose_chq');

    var $hour = $('.js_hour_chq');
    var $min = $('.js_min_chq');



    //全局对象，用于存放提交表单的参数
    var global = {};
    global.selectedMethod = [];//已选方法
    global.sex = 'M';
    global.patientTypeId = 0;//默认病人类型为门诊，0-门诊，1-住院，2-体检
    global.emergencyId = 1;//紧急程度，1-普通，2-急诊
    
    global.reqHospital = ''//开单医院
    global.reqDept = '' //开单科室
    global.reqDoctor = ''; //开单医师
    global.rispatientId = '';//影像号
    global.thirdPatientId = ''; //his病人号 
    global.reqDateTime = '';//申请时间
    global.examinePrice = ''//检查费用
    global.hisSheetId = []; //申请单号^检查项|"多个直接拼接

    global.examDeptId = '';//检查科室id
    global.modalityId = '';//检查类型id
    global.modalityType = '';//检查类型
    global.modalityName = '';//检查设备
    global.reportType = 0;// 报告类型



    get_hospital() //获取开单医院


    get_checkDept() // 获取检查科室
    eleTableQuery() // 表格查询




    $('.patient_type').on('click',function(e) {
        e.stopPropagation();
        global.patientTypeId = $(this).data('patienttype');
        $(this).addClass('patient_type_ac').siblings().removeClass('patient_type_ac');
    })

    $('.urgency_item').on('click',function(e) {
        e.stopPropagation();
        global.emergencyId = $(this).data('emergencyid');
        $(this).addClass('urgency_item_selected').siblings().removeClass('urgency_item_selected');
    })




    $appBtn.on('click', function(e) {
        e.stopPropagation();

        defHospital()
        defCheck()
        
        $appRegister.show();
        $mask.show()
        
    })

    $addformClose.on('click', function(e) {
        e.stopPropagation();
        global.hisSheetId = [];
        $mask.hide()
        $addForm.hide()
    })
    $addFormCacle.on('click', function(e) {
        e.stopPropagation();
        global.hisSheetId = [];
        $mask.hide()
        $addForm.hide()
    })

    



    // 表格查询请求
    function eleTableQuery() {
        var pageNo = $nowPage.text()
        var pageSize = $pageSize.text();
        var queryContentType = $queryContentType.text();//查询类型
        var queryContent = $queryContent.val(); // 查询内容
        var type = $type.text(); // 病人类型
        var startTime = $startTime.val(); //开始日期
        var endTime = $endTime.val(); //结束日期

        $table.empty()
        $loadingICon.show();


        $.get(api.platformRequestInfoAll, {
            "pageNo":pageNo,
            "pageSize":pageSize,
            "queryContentType": queryContentType,
            "queryContent": queryContent,
            "type": type,
            "startDate": startTime,
            "endDate": endTime,
            "reqType": "新申请"
        },function(data){
            if(data.code === 200) {
                $loadingICon.hide();
                var headArr = data.data.tableHead; // 表头数组
                var tableData = data.data.tableData; // 表格数组
                var headList = []; // 存放标题关键字

                $totalPage.text(data.data.totalPage); // 总页码赋值

                var str = '<thead>';
                $.each(headArr,function(index,item){
                    str += '<th>'+item.colName+'</th>'
                    headList.push(item.fieldName)
                })
                str +='<th class="tableFix_zn">操作</th><th><div class="zhanwei_zn"></div></th></thead>'

                var td = '' // 存放表格doom元素

                for(var j=0;j<tableData.length;j++) {
                    td += '<tr>'
                    for(var i=0;i<headList.length;i++) {
                        td += '<td>'+tableData[j][headList[i]] + '</td>'
                    }

                    td += '<td class="tableFix_zn"><div class="fixBox_zn"><span class="toCheck_OPC"></span>';
                    td += '<span class="blue_bg_chq js_appBtn_chq" '+ 'data-name='+ tableData[j].Name+' '+'data-id='+ tableData[j].HISSheetID+'>预约登记</span></div></td><td><div class="zhanwei_zn"></div></td></tr>'
                    
                }
                
                $table.append(str + td)


                $('.js_appBtn_chq').on('click',function(e){
                    e.stopPropagation();
                    var name = $(this).data('name');
                    var id = $(this).data('id');
                    addFormQuery(id,name)
                })

            }else {
                alert(data.message);
            }
            
        });

    }

    $searchBtn.on('click',function(e){
        e.stopPropagation();
        eleTableQuery()
    })

    $prev.on('click',function(e){
        e.stopPropagation();
        var nowPage = Number($nowPage.text());
        if(nowPage === 1) {
            return;
        }
        $nowPage.text(nowPage-1);
        eleTableQuery()
    })

    $next.on('click',function(e){
        e.stopPropagation();
        var totalPage = Number($totalPage.text());
        var nowPage = Number($nowPage.text());
        if(nowPage+1 > totalPage) {
            return;
        }
        $nowPage.text(nowPage+1);
        eleTableQuery()
    })

    $gotoBtn.on('click',function(e) {
        e.stopPropagation();
        var totalPage = Number($totalPage.text());
        var gotoPage = Number($gotoInput.val())
        if(gotoPage > totalPage) {
            return;
        }
        $nowPage.text(gotoPage);
        eleTableQuery()
    })


    


    // 渲染合并/拆分申请单卡片
    function addFormQuery(hisSheetId,name) {
        var url = api.platformRequestInfo + hisSheetId;
        var str = ''
        $.get(url, {},function(data){
            if(data.code === 200) {
                var data = data.data;
                $.each(data,function(index,item){
                    str += '<div class="m-requisitionDiv"'+' '+'data-projectid='+item.projectid+' '+'data-patientid='+item.patientid+' '+'data-TotalCost='+item.TotalCost;
                    str += '><img src="../img/choosed.png" class="m-shape1_zn" /><div class="s-add_zn"><span>添加</span></div><span class="s-userName_zn">' + name + '</span>';
                    str += '<span class="s-belly_zn">' + item.projectname + '</span>';
                    str += '<span class="s-appNumber_zn">申请单号：' + item.hissheetid + '</span></div>';
                })
                $('.m-requisitionList_zn').empty();
                $('.m-requisitionList_zn').append(str);
                $mask.show();
                $addForm.show();

                var patientid = ''
                var hisProjectIds = []; // 提前定义要传的项目id数组
                
                // 如果只有一个，默认选中
                if(data.length === 1) {
                    $('.m-requisitionDiv').children('img').show();
                    $('.m-requisitionDiv').children('.s-add_zn').hide();
                    hisProjectIds.push($('.m-requisitionDiv').data('projectid'));
                    global.hisSheetId.push(hisSheetId+'^'+$('.m-requisitionDiv').data('projectid')+'|');
                    patientid = $('.m-requisitionDiv').data('patientid');

                    global.examinePrice = $('.m-requisitionDiv').data('totalcost');

                }
                // 如果大于1个，默认选中第一个
                if(data.length > 1) {
                    console.log($('.m-requisitionDiv'))
                    $($('.m-requisitionDiv')[0]).children('img').show();
                    $($('.m-requisitionDiv')[0]).children('.s-add_zn').hide();
                    hisProjectIds.push($($('.m-requisitionDiv')[0]).data('projectid'));
                    global.hisSheetId.push(hisSheetId+'^'+$($('.m-requisitionDiv')[0]).data('projectid')+'|');
                    patientid = $($('.m-requisitionDiv')[0]).data('patientid');
                    global.examinePrice = $($('.m-requisitionDiv')[0]).data('totalcost');

                }

                $('.m-requisitionDiv').on('click',function(e){
                    e.stopPropagation();
                    patientid = $(this).data('patientid');
                    // var totalcost = $(this).data('totalcost');
                    var projectid = $(this).data('projectid');

                    // 如果已选中，点击去除选中图标，从数组中去除该id
                    if(hisProjectIds.indexOf(projectid) > -1) {
                        $('.m-requisitionDiv').children('img').hide();
                        $('.m-requisitionDiv').children('.s-add_zn').show();
                        // hisProjectIds.splice($.inArray(projectid,hisProjectIds),1)
                        // global.hisSheetId.splice($.inArray(hisSheetId+'^'+projectid+'|',global.hisSheetId),1)

    


                    } else {
                        $('.m-requisitionDiv').children('img').show();
                        $('.m-requisitionDiv').children('.s-add_zn').hide();
                        hisProjectIds.push(projectid)
                        global.hisSheetId.push(hisSheetId+'^'+projectid+'|');

                    }

                    // 如果没有选择任何卡片，下一步按钮无法点击
                    if(hisProjectIds.length === 0) {
                        $nextPop.css('background','gray').css('cursor','not-allowed').css('pointer-events','none');
                    } else {
                        $nextPop.css('background','#0099ff').css('cursor','pointer').css('pointer-events','all');
                    }

                })

                $nextPop.off("click").on('click',function(e) {
                    e.stopPropagation();
                    appFormAtart(hisSheetId,patientid,hisProjectIds)
                    $mask.hide()
                    $addForm.hide()
                })
                
            }else {
                alert(data.message);
            }
            
        });
    }
    
    

    

    function appFormAtart(hisSheetId,hisPatientId,hisProjectIds) {
        $.get(api.reservationInitInfo, {
            "hisSheetId":hisSheetId,
            "hisPatientId":hisPatientId,
            "hisProjectIds": hisProjectIds.toString()
        },function(data){
            if(data.code === 200) {
                // console.log(data)

                var medicareInfo = data.data.medicareInfo;
                var patientInfo = data.data.patientInfo;
                
                $patientName.val(patientInfo.patientName); //患者姓名赋值
                get_pinYin(patientInfo.patientName); // 根据姓名获取拼音
                $idcard.val(patientInfo.idcard);//身份证号赋值
                $birthday.val(patientInfo.birthday); // 出生日期赋值
                $weight.val(patientInfo.weight); // 体重赋值
                $medicareCardNumber.val(patientInfo.patientInfo);//医保卡号赋值
                $selfPayCardNumber.val(patientInfo.selfPayCardNumber);//自费卡号赋值
                $phoneNumber.val(patientInfo.phoneNumber);// 手机号赋值
                $familyPhone.val(patientInfo.familyPhone);// 家属电话赋值
                $company.val(patientInfo.company);// 工作单位赋值
                $address.val(patientInfo.address);// 联系地址赋值

                $patientNumber.val(medicareInfo.patientNumber) //住院号
                $hospitalizedNumber.val(medicareInfo.hospitalizedNumber);//住院次数
                $ward.val(medicareInfo.ward);//院区
                $bedNo.val(medicareInfo.bedNo);//床号
                $medicalRecordDescription.val(medicareInfo.medicalRecordDescription)//病历描述
                $clinicDiagnose.val(medicareInfo.clinicDiagnose);//临床诊断

                
                global.rispatientId = patientInfo.patientId//将ris 的patientId放到全局上
                $risPatientId.text(global.rispatientId);
                // getPatientIdByThirdPatientID(patientInfo.patientId) //获取影像号
                global.reqDateTime = medicareInfo.reqDateTime;//申请时间

                global.sex = patientInfo.sex; //性别
                global.patientTypeId = medicareInfo.patientTypeId;//病人类型
                global.emergencyId = medicareInfo.emergencyId;//紧急程度
                global.thirdPatientId = patientInfo.thirdPatientId;//his 病人号

                global.reqHospital = medicareInfo.reqHospital;//开单医院
                global.reqDept = medicareInfo.reqDept;//开单科室
                global.reqDoctor = medicareInfo.reqDoctor;//开单医师

                global.examDeptId = medicareInfo.examDeptId;//检查科室id
                global.modalityId = medicareInfo.modalityId;//检查类型id
                global.modalityType = medicareInfo.modalityType;//检查类型
                global.modalityName = medicareInfo.modalityName;//检查设备
                

                
                

                get_reqDept(global.reqHospital);
                get_reqDoctor(global.reqHospital,global.reqDept);
                get_checkType(global.examDeptId);
                get_checkModality(global.examDeptId,global.modalityType)

                $('.js_hospitalSelect').find('.cosSpan_chq').text(global.reqHospital);
                $('.js_reqDeptSelect').find('.cosSpan_chq').text(global.reqDept);
                $('.js_reqDoctorSelect').find('.cosSpan_chq').text(global.reqDoctor);
               
                changeSelected(global.examDeptId,'.js_checkDept');
                $('.js_checkType').find('.cosSpan_chq').text(global.modalityType);
                $('.js_checkModality').find('.cosSpan_chq').text(global.modalityName);

                sexDom(patientInfo.sex);//修改性别状态
                patientTypeDom(medicareInfo.patientTypeId);//修改病人类型状态
                urgencyDom(medicareInfo.emergencyId);//修改紧急程度状态

                var birthdayTime = patientInfo.birthdayTime; //出生时间处理
                if(birthdayTime.length === 4) {
                    $hour.val(a[0]+a[1]);
                    $min.val(a[2]+a[3]);
                } else {
                    $hour.val('');
                    $min.val('');
                }

                
                get_examPartAndMethod(global.modalityId,global.modalityType,'')

                global.selectedMethod = medicareInfo.partAndMethodList;//已选方法|部位

                // 点击可选项渲染右侧已选框
                var str = '';
                $.each(global.selectedMethod,function(index,item) {
                    str+='<li class="selected_item"><img src="../img/close_small.png">' + item + '</li>'
                })
                $('.Methods_list').empty();
                $('.Methods_list').append(str);

                
                

                $appRegister.show();
                $mask.show();
            }else {
                alert(data.message);
            }
            
        });
    }


    function clearData() {
        var inputList = $(".js_appRegister_chq input[type='text'] ");
        var cosSpanList = $('.js_appRegister_chq .cosSpan_chq');
        // 清空所有输入框
        $.each(inputList,function(index,item){
            $(item).val('');
        })

        // 清空全局数据
        for(let key in global){
            if(global[key] instanceof Array) {
                global[key]  = []
            }else {
                if(key === 'reportType') {
                    global[key]  = 0;
                } else if(key === 'sex') {
                    global[key] = "M"
                } else if(key === 'patientTypeId') {
                    global[key] = 0
                } else if(key === 'emergencyId') {
                    global[key] = 1
                } else {
                    global[key]  = '';
                }
                
            }
            
        }
        

        $.each(cosSpanList,function(index,item){

            if($(item).parents('.cosSelectBox_chq').hasClass('js_reportType')) {
                return;
            } 
            $(item).text('请选择')
        })

        $('.Methods_list').empty();
        $('.js_risPatientId_chq').text('')

    }
    // 关闭弹窗2
    function close_appRegister() {

        release(global.rispatientId);
        
        clearData()
        $appRegister.hide();
        $mask.hide();
    }



    $('.is_close_appRegister').on('click',close_appRegister)
    $('.is_cacle_appRegister').on('click',close_appRegister)

    $('.js_submit_chq').off().on('click',function(){
        post_patientInfo()
        post_requestInfo()

        clearData()
        $appRegister.hide();
        $mask.hide();
    })

    function post_patientInfo(){
        var pinyinList = $('.js_pingyin_chq').val().split("");
        var otherNumber3 = '';
        for(var i =0;i<pinyinList.length;i++) {
            if(pinyinList[i] > "A" && pinyinList[i] < 'Z'){
                otherNumber3 += pinyinList[i];
            }
        }

        $.post(api.patients, {
            patientId: global.rispatientId,
            patientName:$patientName.val(),
            pinYin: $('.js_pingyin_chq').val(),
            sex: global.sex,
            birthday: $birthday.val(),
            IDCard: $idcard.val(),
            address:$address.val(),
            phoneNumber:$phoneNumber.val(),
            otherNumber3:otherNumber3,
            birthdayTime:$hour.val()+$min.val(),
            familyPhone:$familyPhone.val(),
            thirdPatientId:global.thirdPatientId,
            medicareCardNumber: $medicareCardNumber.val()
        },function(data){
            if(data.code === 200) {
                
                

            }else {
                alert(data.message);
            }
            
        });
    }

    function post_requestInfo(){
        $.post(api.requestInfo, {
            patientId: global.rispatientId,
            patientTypeId: global.patientTypeId,
            emergencyId:global.emergencyId,
            patientName:$patientName.val(),
            patientNumber: $patientNumber.val(),
            examDeptId: global.examDeptId,
            modalityId:global.modalityId,
            modalityType:global.modalityType,
            reqHospital:global.reqHospital,
            reqDept:global.reqDept,
            reqDoctor: global.reqDoctor,
            examPartAndMethods:global.selectedMethod.toString(),
            medicalRecordDescription: $medicalRecordDescription.val(),//病历描述,
            clinicDiagnose:$clinicDiagnose.val(),//临床诊断
            ward:$ward.val(),
            bedNo:$bedNo.val(),
            hospitalizedNumber:$hospitalizedNumber.val(),
            stateId:20,
            examBodyPartNum:global.selectedMethod.length,
            examinePrice: global.examinePrice,
            pinYin: $('.js_pingyin_chq').val(),
            sex: global.sex,
            birthday: $birthday.val(),

            hisSheetId: global.hisSheetId.toString(),
            // hisSheetId: '4^030130120004|',
            
            reqDateTime: global.reqDateTime,

            reportType: global.reportType,
            medicareCardNumber: $medicareCardNumber.val(),
            birthdayTime:$hour.val()+$min.val(),
            familyPhone:$familyPhone.val(),
            status:10,
            electricType:1,

            
            
            thirdPatientId:global.thirdPatientId,
            


            

            
            

        },function(data){
            if(data.code === 200) {
                
                

            }else {
                alert(data.message);
            }
            
        });
    }




    // 修改检查科室已选文字
    function changeSelected(id,className){
        var options = $(className).find('li');
        for(var i=0;i<options.length;i++) {
            if($(options[i]).data('key') === id) {
                $(className).find('.cosSpan_chq').text($(options[i]).text())
            }
        }
    }


    var $sex = $('.sex');
    var $patient_type = $('.patient_type');
    var $urgency_item = $('.urgency_item');
    function sexDom(sex) {
        for(var i=0;i<$sex.length;i++) {
            if($($sex[i]).data('sex') === sex) {
                $($sex[i]).addClass('sex_ac').siblings().removeClass('sex_ac');
            }
        }
    }

    function patientTypeDom(patientTypeId) {
        for(var i=0;i<$patient_type.length;i++) {
            if($($patient_type[i]).data('patienttype') === patientTypeId) {
                $($patient_type[i]).addClass('patient_type_ac').siblings().removeClass('patient_type_ac');
            }
        }
    }

    function urgencyDom(emergencyId) {
        for(var i=0;i<$urgency_item.length;i++) {
            if($($urgency_item[i]).data('emergencyid') === emergencyId) {
                $($urgency_item[i]).addClass('urgency_item_selected').siblings().removeClass('urgency_item_selected');
            }
        }
    }

    $sex.on('click',function(e){
        e.stopPropagation()
        var sex = $(this).data('sex');
        global.sex = sex;
        $(this).addClass('sex_ac').siblings().removeClass('sex_ac');
    })



    // 根据hisPatientId获取rispatientId
    function getPatientIdByThirdPatientID(hisPatientId) {
        $.get(api.getPatientIdByThirdPatientID, {
            hisPatientId:hisPatientId
        },function(data){
            if(data.code === 200) {
               global.rispatientId = data.data;//将ris 的patientId放到全局上
               $risPatientId.text(global.rispatientId);
            }else {
                alert(data.message);
            }
            
        });
    }

    // 取消和关闭弹窗接触占用接口
    function release(rispatientId) {
        var url = api.release+'/'+rispatientId
        $.get(url, {},function(data){
            if(data.code === 200) {
            //    console.log(data)
            }else {
                alert(data.message);
            }
            
        });
    }










    var $daySelect = $('.js_daySelect');  //选择框按钮
    var $daySelect_box = $daySelect.find('.cosSelect_chq') // 下拉选项框
    var $daySelect_options = $daySelect.find('li') // 选项组
    var $daySelect_text = $daySelect.find('.cosSpan_chq') //按钮文字
    var $daySelect_icon = $daySelect.find('.cosSpanImg_chq') //按钮图标

    // 今天选择框
    $daySelect.on('click',function(e) {
        e.stopPropagation();
        if($daySelect_box.css('display') === 'none') {
            $daySelect_box.show()
            $daySelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $daySelect_box.hide()
            $daySelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    $daySelect_options.on('click',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        $daySelect_text.text(text)
        $daySelect_box.hide()
        $daySelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    //就诊类型选择框
    var $clinicTypeSelect = $('.js_clinicTypeSelect');
    var $clinicTypeSelect_box = $clinicTypeSelect.find('.cosSelect_chq')
    var $clinicTypeSelect_options = $clinicTypeSelect.find('li')
    var $clinicTypeSelect_text = $clinicTypeSelect.find('.cosSpan_chq')
    var $clinicTypeSelect_icon = $clinicTypeSelect.find('.cosSpanImg_chq')

    $clinicTypeSelect.on('click' ,function(e) {
        e.stopPropagation();
        if ($clinicTypeSelect_box.css('display') === 'none') {
            $clinicTypeSelect_box.show()
            $clinicTypeSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        }else{
            $clinicTypeSelect_box.hide()
            $clinicTypeSelect_icon.removeClass('downImg_chq').addClass('downImg_chq')
        }
    })

    $clinicTypeSelect_options.on('click',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        $clinicTypeSelect_text.text(text)
        $clinicTypeSelect_box.hide()
        $clinicTypeSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })

    // 紧急度选择框
    var $urgentSelect = $('.js_urgentSelect');  //选择框按钮
    var $urgentSelect_box = $urgentSelect.find('.cosSelect_chq') // 下拉选项框
    var $urgentSelect_options = $urgentSelect.find('li') // 选项组
    var $urgentSelect_text = $urgentSelect.find('.cosSpan_chq') //按钮文字
    var $urgentSelect_icon = $urgentSelect.find('.cosSpanImg_chq') //按钮图标


    $urgentSelect.on('click',function(e) {
        e.stopPropagation();
        if($urgentSelect_box.css('display') === 'none') {
            $urgentSelect_box.show()
            $urgentSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $urgentSelect_box.hide()
            $urgentSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    $urgentSelect_options.on('click',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        $urgentSelect_text.text(text)
        $urgentSelect_box.hide()
        $urgentSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })

    //患者姓名下拉选择框
    var $patientNameSelect = $('.js_patientNameSelect');
    var $patientNameSelect_box = $patientNameSelect.find('.cosSelect_chq')
    var $patientNameSelect_options = $patientNameSelect.find('li')
    var $patientNameSelect_text = $patientNameSelect.find('.cosSpan_chq')
    var $patientNameSelect_icon = $patientNameSelect.find('.cosSpanImg_chq')

    $patientNameSelect.on('click',function(e) {
        e.stopPropagation();
        if($patientNameSelect_box.css('display') === 'none') {
            $patientNameSelect_box.show()
            $patientNameSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        }else{
            $patientNameSelect_box.hide()
            $patientNameSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    $patientNameSelect_options.on('click',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        $patientNameSelect_text.text(text)
        $patientNameSelect_box.hide()
        $patientNameSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })
   



    // 表格每页行数选择框
    var $pageNumSelect = $('.js_pageNumSelect');  //选择框按钮
    var $pageNumSelect_box = $pageNumSelect.find('.cosSelect_chq') // 下拉选项框
    var $pageNumSelect_options = $pageNumSelect.find('li') // 选项组
    var $pageNumSelect_text = $pageNumSelect.find('.cosSpan_chq') //按钮文字
    var $pageNumSelect_icon = $pageNumSelect.find('.cosSpanImg_chq') //按钮图标


    $pageNumSelect.on('click',function(e) {
        e.stopPropagation();
        if($pageNumSelect_box.css('display') === 'none') {
            $pageNumSelect_box.show()
            $pageNumSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $pageNumSelect_box.hide()
            $pageNumSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    $pageNumSelect_options.on('click',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        $pageNumSelect_text.text(text)
        $nowPage.text('1')
        $pageNumSelect_box.hide()
        $pageNumSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        eleTableQuery()
    })



    // 开单医院选择框
    var $hospitalSelect = $('.js_hospitalSelect');  //选择框按钮
    var $hospitalSelect_box = $hospitalSelect.find('.cosSelect_chq') // 下拉选项框
    var $hospitalSelect_text = $hospitalSelect.find('.cosSpan_chq') //按钮文字
    var $hospitalSelect_icon = $hospitalSelect.find('.cosSpanImg_chq') //按钮图标


    $hospitalSelect.on('click',function(e) {
        e.stopPropagation();
        if($hospitalSelect_box.css('display') === 'none') {
            $hospitalSelect_box.show()
            $hospitalSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $hospitalSelect_box.hide()
            $hospitalSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 开单医院点击
    $hospitalSelect.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        $('.js_reqDeptSelect').find('.cosSpan_chq').text('请选择')
        $('.js_reqDoctorSelect').find('.cosSpan_chq').text('请选择')
        global.reqDoctor = '';
        global.reqDept = '';
        global.reqHospital = key;
        get_reqDept(key)

        $hospitalSelect_text.text(text)
        $hospitalSelect_box.hide()
        $hospitalSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    // 开单科室选择框
    var $reqDoctorSelect = $('.js_reqDeptSelect');  //选择框按钮
    var $reqDoctorSelect_box = $reqDoctorSelect.find('.cosSelect_chq') // 下拉选项框
    var $reqDoctorSelect_text = $reqDoctorSelect.find('.cosSpan_chq') //按钮文字
    var $reqDoctorSelect_icon = $reqDoctorSelect.find('.cosSpanImg_chq') //按钮图标


    $reqDoctorSelect.on('click',function(e) {
        e.stopPropagation();
        if($reqDoctorSelect_box.css('display') === 'none') {
            $reqDoctorSelect_box.show()
            $reqDoctorSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $reqDoctorSelect_box.hide()
            $reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 开单科室点击
    $reqDoctorSelect.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        $('.js_reqDoctorSelect').find('.cosSpan_chq').text('请选择')
        global.reqDoctor = '';
        global.reqDept = key;
        get_reqDoctor($hospitalSelect_text.text(),key)

        $reqDoctorSelect_text.text(text)
        $reqDoctorSelect_box.hide()
        $reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    // 开单医生选择框
    var $js_reqDoctorSelect = $('.js_reqDoctorSelect');  //选择框按钮
    var $js_reqDoctorSelect_box = $js_reqDoctorSelect.find('.cosSelect_chq') // 下拉选项框
    var $js_reqDoctorSelect_text = $js_reqDoctorSelect.find('.cosSpan_chq') //按钮文字
    var $js_reqDoctorSelect_icon = $js_reqDoctorSelect.find('.cosSpanImg_chq') //按钮图标


    $js_reqDoctorSelect.on('click',function(e) {
        e.stopPropagation();
        if($js_reqDoctorSelect_box.css('display') === 'none') {
            $js_reqDoctorSelect_box.show()
            $js_reqDoctorSelect_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $js_reqDoctorSelect_box.hide()
            $js_reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 开单医生点击
    $js_reqDoctorSelect.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        global.reqDoctor = key;
        $js_reqDoctorSelect_text.text(text)
        $js_reqDoctorSelect_box.hide()
        $js_reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    // 检查科室选择框
    var $jcheckDept = $('.js_checkDept');  //选择框按钮
    var $jcheckDept_box = $jcheckDept.find('.cosSelect_chq') // 下拉选项框
    var $jcheckDept_text = $jcheckDept.find('.cosSpan_chq') //按钮文字
    var $jcheckDept_icon = $jcheckDept.find('.cosSpanImg_chq') //按钮图标


    $jcheckDept.on('click',function(e) {
        e.stopPropagation();
        if($jcheckDept_box.css('display') === 'none') {
            $jcheckDept_box.show()
            $jcheckDept_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $jcheckDept_box.hide()
            $jcheckDept_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 检查科室点击
    $jcheckDept.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        $('.js_checkType').find('.cosSpan_chq').text('请选择')
        $('.js_checkModality').find('.cosSpan_chq').text('请选择')
        global.examDeptId = key;
        global.modalityId = '';
        global.modalityType = '';
        global.modalityName = '';

        get_checkType(key);
        $jcheckDept.data('key',key)
        $jcheckDept_text.text(text)
        $jcheckDept_box.hide()
        $jcheckDept_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })





    // 检查类型选择框
    var $checkType = $('.js_checkType');  //选择框按钮
    var $checkType_box = $checkType.find('.cosSelect_chq') // 下拉选项框
    var $checkType_text = $checkType.find('.cosSpan_chq') //按钮文字
    var $checkType_icon = $checkType.find('.cosSpanImg_chq') //按钮图标


    $checkType.on('click',function(e) {
        e.stopPropagation();
        if($checkType_box.css('display') === 'none') {
            $checkType_box.show()
            $checkType_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $checkType_box.hide()
            $checkType_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 事件委托
    $checkType.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        $('.js_checkModality').find('.cosSpan_chq').text('请选择')
        global.modalityName = '';
        global.modalityId = '';
        global.modalityType = key;
        get_checkModality(global.examDeptId,key)
        $checkType_text.text(text)
        $checkType_box.hide()
        $checkType_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    // 检查设备选择框
    var $checkModality = $('.js_checkModality');  //选择框按钮
    var $checkModality_box = $checkModality.find('.cosSelect_chq') // 下拉选项框
    var $checkModality_text = $checkModality.find('.cosSpan_chq') //按钮文字
    var $checkModality_icon = $checkModality.find('.cosSpanImg_chq') //按钮图标


    $checkModality.on('click',function(e) {
        e.stopPropagation();
        if($checkModality_box.css('display') === 'none') {
            $checkModality_box.show()
            $checkModality_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $checkModality_box.hide()
            $checkModality_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 事件委托
    $checkModality.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var modalityid  = $(this).data('modalityid');
        global.modalityId = modalityid;
        global.modalityName = text;
        $checkModality_text.text(text)
        $checkModality_box.hide()
        $checkModality_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })


    // 报告类型选择框
    var $reportType = $('.js_reportType');  //选择框按钮
    var $reportType_box = $reportType.find('.cosSelect_chq') // 下拉选项框
    var $reportType_text = $reportType.find('.cosSpan_chq') //按钮文字
    var $reportType_icon = $reportType.find('.cosSpanImg_chq') //按钮图标


    $reportType.on('click',function(e) {
        e.stopPropagation();
        if($reportType_box.css('display') === 'none') {
            $reportType_box.show()
            $reportType_icon.removeClass('downImg_chq').addClass('upImg_chq')
        } else {
            $reportType_box.hide()
            $reportType_icon.removeClass('upImg_chq').addClass('downImg_chq')
        }
    })

    // 事件委托
    $reportType.on('click','li',function(e) {
        e.stopPropagation();
        var text = $(this).text()
        var key  = $(this).data('key');
        global.reportType = key;

        $reportType_text.text(text)
        $reportType_box.hide()
        $reportType_icon.removeClass('upImg_chq').addClass('downImg_chq')
    })





    
    function defHospital(){
        $.get(api.hospital, {
            showType:''
        },function(data){
            if(data.code === 200) {
                var hlist = data.data;
                global.reqHospital = hlist[0].key;  //开单医院赋值
                $('.js_hospitalSelect').find('.cosSpan_chq').text(hlist[0].value);
                // 渲染选择框dom
                selectDom('.js_hospitalSelect',hlist)

                $.get(api.reqDept, {
                    showType:'',
                    reqHospital: global.reqHospital
                },function(data){
                    if(data.code === 200) {
                        var dlist = data.data;
                        global.reqDept = dlist[0].key;
                        $('.js_reqDeptSelect').find('.cosSpan_chq').text(dlist[0].value);
                        // 渲染选择框dom
                        selectDom('.js_reqDeptSelect',dlist)


                        $.get(api.reqDoctor, {
                            showType:'',
                            reqHospital: global.reqHospital,
                            reqDept :global.reqDept 
                        },function(data){
                            if(data.code === 200) {
                                var list = data.data;
                                global.reqDoctor = list[0].key
                                $('.js_reqDoctorSelect').find('.cosSpan_chq').text(list[0].value);
                                selectDom('.js_reqDoctorSelect',list)
                                
                               
                
                            }else {
                                alert(data.message);
                            }
                            
                        });

        
                    }else {
                        alert(data.message);
                    }
                    
                });


            }else {
                alert(data.message);
            }
            
        });
    }

    function defCheck(){
        $.get(api.checkDept, {
            showType:''
        },function(data){
            if(data.code === 200) {
                var deplist = data.data;
                global.examDeptId = deplist[0].key;
                $('.js_checkDept').find('.cosSpan_chq').text(deplist[0].value)
                // 渲染选择框dom
                selectDom('.js_checkDept',deplist)

                $.get(api.checkType, {
                    showType:'',
                    departmentId:global.examDeptId
                },function(data){
                    if(data.code === 200) {
                        var typelist = data.data;
                        global.modalityType = typelist[0].key;
                        $('.js_checkType').find('.cosSpan_chq').text(typelist[0].value)
                        // 渲染选择框dom
                        selectDom('.js_checkType',typelist)

                        $.get(api.checkModality, {
                            modalityRemark:global.modalityType,
                            departmentId:global.examDeptId
                        },function(data){
                            if(data.code === 200) {
                                var list = data.data;
                                global.modalityid = list[0].modalityid;
                                global.modalityName = list[0].modalityName;
                                $('.js_checkModality').find('.cosSpan_chq').text(list[0].modalityName)
                
                                
                                var $ul = $('.js_checkModality').find('ul');
                                var str = '';
                                $.each(list,function(index,item){
                                    str += '<li' + ' '+ 'data-modalityId=' + item.modalityId +'>' + item.modalityName+'</li>';
                                })
                                $ul.empty();
                                $ul.append(str)
                
                
                            }else {
                                alert(data.message);
                            }
                            
                        });
        
                    }else {
                        alert(data.message);
                    }
                    
                });

            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取开单医院
    function get_hospital(){
        $.get(api.hospital, {
            showType:''
        },function(data){
            if(data.code === 200) {
                var list = data.data;
                // 渲染选择框dom
                selectDom('.js_hospitalSelect',list)

            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取开单科室
    function get_reqDept(reqHospital){
        $.get(api.reqDept, {
            showType:'',
            reqHospital: reqHospital
        },function(data){
            if(data.code === 200) {
                var list = data.data;
                // 渲染选择框dom
                selectDom('.js_reqDeptSelect',list)

            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取开单医师
    function get_reqDoctor(reqHospital,reqDept ){
        $.get(api.reqDoctor, {
            showType:'',
            reqHospital: reqHospital,
            reqDept :reqDept 
        },function(data){
            if(data.code === 200) {
                var list = data.data;
                selectDom('.js_reqDoctorSelect',list)
                
               

            }else {
                alert(data.message);
            }
            
        });
    }


    // 获取检查科室
    function get_checkDept(){
        $.get(api.checkDept, {
            showType:''
        },function(data){
            if(data.code === 200) {
                var list = data.data;

                // 渲染选择框dom
                selectDom('.js_checkDept',list)

            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取检查类型
    function get_checkType(departmentId){
        $.get(api.checkType, {
            showType:'',
            departmentId:departmentId
        },function(data){
            if(data.code === 200) {
                var list = data.data;
                // 渲染选择框dom
                selectDom('.js_checkType',list)

            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取检查设备
    function get_checkModality(departmentId,modalityRemark){
        $.get(api.checkModality, {
            modalityRemark:modalityRemark,
            departmentId:departmentId
        },function(data){
            if(data.code === 200) {

                var list = data.data;
                var $ul = $('.js_checkModality').find('ul');
                var str = '';
                $.each(list,function(index,item){
                    str += '<li' + ' '+ 'data-modalityId=' + item.modalityId +'>' + item.modalityName+'</li>';
                })
                $ul.empty();
                $ul.append(str)


            }else {
                alert(data.message);
            }
            
        });
    }

    // 获取拼音接口
    function get_pinYin(wordList){
        console.log(wordList)
        var str = ''
        for(var i=0;i<wordList.length;i++) {
            if (wordList[i].match(/^[ ]*$/)) {
                return;
            }

            $.get(api.pinYin, {
                word:wordList[i]
            },function(data){
                if(data.code === 200) {
                    
                    if(data.data.length>=1) {
                        str += data.data[0].pinYin+' ';
                    }
                    $('.js_pingyin_chq').val(str);
    
                }else {
                    // alert(data.message);
                }
                
            });
        }
        
        
    }


    // 简码搜索事件
    $('.js_fastKeyInput').bind('input propertychange', function() {
        get_examPartAndMethod(global.modalityId,global.modalityType,$(this).val())
    });


    $('.js_patientName_chq').focus(function (e){
        e.stopPropagation();
    })
    $('.js_patientName_chq').blur(function (e){
        e.stopPropagation();

    })
    // 患者姓名输入事件
    $('.js_patientName_chq').bind('input propertychange', function() {
        var val = $(this).val()
        if(!val) {
            $('.js_pingyin_chq').val('');
            return
        }
        var valList = val.split();
        get_pinYin(val)
        

        
        // 光标获取时，判断用户在输入，失去焦点则从头开始，可用一个全局变量判断
        // console.log($(this).val())
    });
    

    // 简码点击选择事件
    $('.methoBox_chq').on('click','.methodItem_chq',function(e){
        e.stopPropagation();
        var key = $(this).data('key');
        
        if(global.selectedMethod.indexOf(key) === -1) {
            global.selectedMethod.push(key);
            $(this).removeClass('methodItem_nomal').addClass('methodItem_selected')
        } else {
            // global.selectedMethod.splice($.inArray(key,global.selectedMethod),1)
            $(this).removeClass('methodItem_selected').addClass('methodItem_nomal')
        }

        // 点击可选项渲染右侧已选框
        var str = '';
        $.each(global.selectedMethod,function(index,item) {
            str+='<li class="selected_item"><img src="../img/close_small.png">' + item + '</li>'
        })
        $('.Methods_list').empty();
        $('.Methods_list').append(str);

    })


    // 已选部位||方法 左侧小x按钮事件
    $('.Methods_list').on('click','img',function(e) {
        e.stopPropagation();
        var key = $(this).parent().text();
        
        if(global.selectedMethod.indexOf(key) === -1) {
            global.selectedMethod.push(key);
        } else {
            // global.selectedMethod.splice($.inArray(key,global.selectedMethod),1)
        }

        // 取消左侧已选项
        var $methodList = $('.methodItem_chq');
        for(var i=0;i<$methodList.length;i++) {
            var $item = $($methodList[i]);
            if($item.text() === key) {
                $item.removeClass('methodItem_selected').addClass('methodItem_nomal')
            }
        }

        // 重新渲染右侧已选框
        var str = '';
        $.each(global.selectedMethod,function(index,item) {
            str+='<li class="selected_item"><img src="../img/close_small.png">' + item + '</li>'
        })
        $('.Methods_list').empty();
        $('.Methods_list').append(str);
    })



    //获取可选部位、方法请求
    function get_examPartAndMethod(modalityId,modalityRemark,fastKey) {
        if(!modalityId) {
            return
        }
        if(!modalityRemark) {
            return
        }
        $('.methoBox_chq').empty();
        $.get(api.examPartAndMethod, {
            showType:'',
            modalityId: modalityId,
            modalityRemark:modalityRemark,
            fastKey:fastKey
        },function(data){
            if(data.code === 200) {
                var list = data.data;
                var str = '';
                $.each(list,function(index,item){
                    str += '<div class="methodItem_chq methodItem_nomal"' + ' ' + 'data-key="' + item.key +'">'+item.value+'</div>'
                })
                $('.methoBox_chq').append(str);
                
                var $methodItem = $('.methodItem_chq');
                for(var i=0;i<$methodItem.length;i++) {
                    if(global.selectedMethod.indexOf($($methodItem[i]).data('key')) > -1) {
                        $($methodItem[i]).removeClass('methodItem_nomal').addClass('methodItem_selected')
                    }
                }

            }else {
                var str = '<div class="noText">'+ data.message+'</div>';
                $('.methoBox_chq').append(str);
            }
            
        });
    }



    // 渲染下拉框dom
    function selectDom(className,list) {
        var $ul = $(className).find('ul');
        var str = '';
        $.each(list,function(index,item){
            str += '<li' + ' '+ 'data-key=' + item.key +'>' + item.value+'</li>';
        })
        if(className === '.js_reqDoctorSelect') {
            if(global.reqDoctor) {
                str += '<li data-key='+ global.reqDoctor+'>'+global.reqDoctor+'</li>'
            }
        }
        
        $ul.empty();
        $ul.append(str)
    }






    // 点击页面其他地方关闭选择下拉框
    $(document).click(function(e) {
        e.stopPropagation();
        $daySelect_box.hide()
        $urgentSelect_box.hide()
        $clinicTypeSelect_box.hide()

        $patientNameSelect_box.hide()
        $pageNumSelect_box.hide()

        $hospitalSelect_box.hide()
        $reqDoctorSelect_box.hide()
        $js_reqDoctorSelect_box.hide()

        $daySelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        $urgentSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        $clinicTypeSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        $pageNumSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')

        $hospitalSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        $reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')
        $js_reqDoctorSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')

        $patientNameSelect_icon.removeClass('upImg_chq').addClass('downImg_chq')

    })
})
